package com.we.tickets.util;

import io.ipfs.api.IPFS;
import io.ipfs.api.MerkleNode;
import io.ipfs.api.NamedStreamable;
import io.ipfs.multihash.Multihash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Component
public class IPFSUtil {
    @Value("${ipfs.config.multi-addr}")
    private String multiAddr;

    private static IPFS ipfs;

    @PostConstruct
    private void getIpfs() {
        ipfs = new IPFS(multiAddr);
    }

    public static String upload(byte[] content) throws IOException {
        NamedStreamable.ByteArrayWrapper wapper = new NamedStreamable.ByteArrayWrapper(content);
        MerkleNode res = ipfs.add(wapper).get(0);
        return res.hash.toString();
    }

    public static byte[] load(String hash) throws IOException {
        return ipfs.cat(Multihash.fromBase58(hash));
    }

}
